package cn.kgc.springboot.controller;

import cn.hutool.core.util.RandomUtil;
import cn.kgc.springboot.entity.User;
import cn.kgc.springboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author: mosin
 * @version: v1.0  2022/8/10
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("test")
    @ResponseBody
    public String test01(){
        return "ok";
    }


    @RequestMapping("login")
    public String login(String username,String password){

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(usernamePasswordToken);
        //认证通过
        return "redirect:/index.html";
    }


    @RequestMapping("register")
    public String register(String username,String password) {
        // 生成随机盐
        String salt = RandomUtil.randomString(5);
        Md5Hash md5Hash = new Md5Hash(password, salt, 1024);
        String newPassword = md5Hash.toHex();
        User user = new User().setUsername(username).setSalt(salt).setPassword(newPassword);
        userService.addUser(user);
        //认证通过
        return "redirect:/login.html";
    }

    @RequestMapping("logout")
    public String logout() {

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        //认证通过
        return "redirect:/login.html";
    }


    @RequiresRoles("admin")
    @RequiresPermissions("user:add")
    @RequestMapping("add")
    public String addUser(){
        System.out.println("用户信息添加成功");
        return "redirect:/success.html";
    }

    @RequiresRoles("admin")
    @RequiresPermissions("user:update")
    @RequestMapping("update")
    public String updateUser(){
        System.out.println("用户信息修改成功");
        return "redirect:/success.html";
    }

    @RequiresRoles("admin")
    @RequiresPermissions("user:delete")
    @RequestMapping("delete")
    public String deleteUser(){
        System.out.println("用户信息删除成功");
        return "redirect:/success.html";
    }


    @RequestMapping("find")
    @RequiresPermissions("user:view")
    public String findUser(){
        System.out.println("用户信息查询成功");
        return "redirect:/success.html";
    }
}
